package be.music.tool.sound;

import java.io.IOException;
import java.net.URL;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class AudioPlayer {

	private static Clip clickClip;

	 
	public static void playSound() {
	 
		Thread t = new Thread(new Runnable() {
			
			@Override
			public void run() {
			
				//TODO: Loading sound should be Thread.
				//TODO: Playing sound should be Thread. Join this Thread with loading Thread.

				Clip clip = null;
			 
			    try {
			       
			        if (clickClip == null) {
			        	/* Create our clip object */
			            clickClip = AudioSystem.getClip();
			         
			            /* Create a URL that points to our file */
			            URL clipURL = AudioPlayer.class.getResource("ShipsBell.wav");
			         
			            /* Open our URL as an AudioStream */
			            AudioInputStream ais = AudioSystem.getAudioInputStream(clipURL);
			         
			            /* Put out audio input stream into our clip */
			            clickClip.open(ais);
			
			        }
			        clip = AudioPlayer.clickClip;
			              
			        
			    } catch (IOException ex) {
			        // ignore any exceptions here, it just won't play the sound
			    } catch (LineUnavailableException ex) {
			        // ignore any exceptions here, it just won't play the sound
			    } catch (UnsupportedAudioFileException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			    
			    if (clip != null) {
			        try {
			            clip.setFramePosition(0);
			            clip.start();
			        } finally {
			            clip = null;
			        }
			    }	
				
			}
		});
		
		t.run();
		
	}

	
}
